window.addEventListener('load', function () {
    // 学员信息表单
    let tbdoy = document.querySelector('tbody')
    // 重置按钮
    let btnreset = document.querySelector('.btnreset')
    // 添加学员按钮
    let btnadd = document.querySelector('.btnadd')
    // 新增模态框确认添加按钮
    let truebtnadd = document.querySelector('.truebtnadd')
    // 新增模态框中的表单
    let form = document.querySelector('.add-form')
    // 省 下拉列表
    let provinceEle = document.querySelector('[name="province"]')
    // 市 下拉列表
    let cityEle = document.querySelector('[name="city"]')
    //区县 下拉列表
    let countyEle = document.querySelector('[name="county"]')
    // 新增或编辑模态框中的标题
    let addModalLabel = document.querySelector('#addModalLabel')
    //姓名
    let name = document.querySelector('[name="name"]')
    //年龄
    let age = document.querySelector('[name="age"]')
    //组号
    let group = document.querySelector('[name="group"]')
    //性别 
    let sexs = document.querySelectorAll('[name="sex"]')
    //手机号
    let phone = document.querySelector('[name="phone"]')
    //期望薪资
    let salary = document.querySelector('[name="salary"]')
    //实际薪资
    let truesalary = document.querySelector('[name="truesalary"]')
    // 编辑时的数据id
    let editid

    // 一：动态渲染
    function init() {
        axios({
            url: '/student/list'
        }).then(({ data: { data } }) => {
            let htmlStr = ''
            data.forEach(function (value, index) {
                htmlStr += `<tr>
                              <th scope="row">${index + 1}</th>
                              <td>${value.name}</td>
                              <td>${value.age}</td>
                              <td>${value.sex}</td>
                              <td>${value.group}</td>
                              <td>${value.phone}</td>
                              <td>${value.salary}</td>
                              <td>${value.truesalary}</td>
                              <td>${value.province + value.city + value.county}</td>
                              <td>
                                <button type="button" class="btn btn-primary btn-sm btnedit"  data-id = '${value.id}'>修改</button>
                                <button type="button" class="btn btn-danger btn-sm btndel"  data-id = '${value.id}'>删除</button>
                              </td>
                            </tr>`
            })
            tbdoy.innerHTML = htmlStr
        })
    }
    init()

    // 省市级联
    // 加载省的数据
    axios({
        url: '/geo/province'
    }).then(res => {
        let htmlstr = '<option selected value="">--省--</option>'
        res.data.forEach(function (value) {
            htmlstr += `<option value="${value}">${value}</option>`
        })
        provinceEle.innerHTML = htmlstr
    })
    // 加载省的市 的数据
    provinceEle.addEventListener('change', function () {
        let pname = provinceEle.value
        // 如果没有选择具体的省，则不进行数据的加载
        if (!pname) {
            cityEle.innerHTML = '<option selected value="">--市--</option>'
            countyEle.innerHTML = `<option selected value="">--区--</option>`
            return
        }
        axios({
            url: '/geo/city',
            params: { pname }
        }).then(res => {
            let htmlstr = '<option selected value="">--市--</option>'
            res.data.forEach(function (value) {
                htmlstr += `<option value="${value}">${value}</option>`
            })
            cityEle.innerHTML = htmlstr
        })
    })
    // 加载省的市的区 的数据
    cityEle.addEventListener('change', function () {
        let pname = provinceEle.value
        let cname = cityEle.value
        if (!cname) {
            countyEle.innerHTML = `<option selected value="">--区--</option>`
            return
        }
        axios({
            url: 'geo/county',
            params: { pname, cname }
        }).then(res => {
            let htmlStr = ''
            res.data.forEach(function (value) {
                htmlStr += `<option value="${value}">${value}</option>`
            })
            countyEle.innerHTML = htmlStr
        })
    })

    // 二：添加学员
    // 点击添加学员按钮弹出模态框
    btnadd.addEventListener('click', function () {
        btnreset.click()
        addModalLabel.innerHTML = '录入新学员'
        truebtnadd.innerHTML = '确认添加'
        $('#addModal').modal('show')
    })

    // 表单数据验证
    function student() {
        return {
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '姓名不能为空',
                        },
                        stringLength: {
                            min: 2,
                            max: 10,
                            message: '姓名长度2~10位'
                        }
                    }
                },
                age: {
                    validators: {
                        notEmpty: {
                            message: '年龄不能为空',
                        },
                        greaterThan: {
                            value: 18,
                            message: '年龄不能小于18岁'
                        },
                        lessThan: {
                            value: 60,
                            message: '年龄不能超过60岁'
                        }
                    }
                },
                sex: {
                    validators: {
                        choice: {
                            min: 1,
                            max: 1,
                            message: '请选择性别'
                        }
                    }
                },
                group: {
                    validators: {
                        notEmpty: {
                            message: '组号不能为空',
                        },
                        regexp: {
                            regexp: /^\d{1,2}$/,
                            message: '请选择有效的组号'
                        }
                    }
                },
                phone: {
                    validators: {
                        notEmpty: {
                            message: '手机号不能为空',
                        },
                        regexp: {
                            regexp: /^1\d{10}$/,
                            message: '请填写有效的手机号'
                        }
                    }
                },
                salary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '期望薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '期望薪资不能高于100000'
                        }
                    }
                },
                truesalary: {
                    validators: {
                        notEmpty: {
                            message: '实际薪资不能为空',
                        },
                        greaterThan: {
                            value: 800,
                            message: '实际薪资不能低于800'
                        },
                        lessThan: {
                            value: 100000,
                            message: '实际薪资不能高于100000'
                        }
                    }
                },
                province: {
                    validators: {
                        notEmpty: {
                            message: '省份必填',
                        },
                    }
                },
                city: {
                    validators: {
                        notEmpty: {
                            message: '市必填',
                        },
                    }
                },
                county: {
                    validators: {
                        notEmpty: {
                            message: '县必填',
                        },
                    }
                },
            }
        }
    }

    // 点击模态框确按钮添加或编辑学员-判断-发起ajax请求
    $('.add-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
        e.preventDefault()
        // 收集用户数据
        let formdata = new FormData(form)
        let data = {}
        formdata.forEach(function (value, key) {
            // console.log(key, value)
            data[key] = value
        })
        if (addModalLabel.innerHTML === '录入新学员') {
            axios({
                url: '/student/add',
                method: 'post',
                data
            }).then(res => {
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                    $('#addModal').modal('hide')
                    init()
                }
            })
        } else {
            // 传id
            data.id = editid
            axios({
                url: '/student/update',
                method: 'put',
                data
            }).then(res => {
                if (res.data.code == 0) {
                    toastr.success(res.data.message)
                    $('#addModal').modal('hide')
                    init()
                }
            })
        }
    })


    // 三：删除学员-事件委托
    tbdoy.addEventListener('click', function (e) {
        if (e.target.classList.contains('btndel')) {
            if (confirm('请问是否真的需要删除？')) {
                let id = e.target.dataset.id
                axios({
                    url: '/student/delete',
                    method: 'DELETE',
                    params: { id }
                }).then(res => {
                    if (res.data.code == 0) {
                        toastr.success(res.data.message)
                        init()
                    }
                })
            }
        }
    })

    // 单击修改按钮，弹出修改模态框
    tbdoy.addEventListener('click', function (e) {
        if (e.target.classList.contains('btnedit')) {
            addModalLabel.innerHTML = '编辑学员'
            truebtnadd.innerHTML = '确认编辑'
            $('#addModal').modal('show')
            // 数据回填
            let id = e.target.dataset.id
            editid = id
            // 发起ajax请求
            axios({
                url: '/student/one',
                params: { id }
            }).then(({ data: { data } }) => {
                // 为元素赋值
                // 常规表单赋值value属性
                name.value = data.name
                age.value = data.age
                salary.value = data.salary
                phone.value = data.phone
                truesalary.value = data.truesalary
                // 单选按钮，给元素添加checked属性--判断
                data.sex === '男' ? (sexs[0].checked = true) : (sexs[1].checked = true)
                // 下拉列表
                group.value = data.group
                provinceEle.value = data.province
                cityEle.innerHTML = `<option selected value="">${data.city}</option>`
                countyEle.innerHTML = `<option selected value="">${data.county}</option>`
            })
        }
    })
})